package mobileann.mafamily.utils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.mofind.android.base.L;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.act.main.FrameworkActivity;
import mobileann.mafamily.entity.NewMessageEntity;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;

/**
 * 获取到应用程序详情信息，如得到当前程序的包名等等。
 * <br>应该已经废弃，但是部分功能仍在使用
 * 
 * <br>主要应用:
 * @see PullLockView
 * @author ADRIAN.2015.7.24.14.38
 */
public class AppInfoUtils {
	private final static String[] pkgs= {"com.tencent.mm", "com.tencent.mobileqq"};

	@TargetApi(21)
	private static boolean needPermissionForBlocking(Context context){
		try {
			PackageManager packageManager = context.getPackageManager();
			ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
			AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
			int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
			return  (mode != AppOpsManager.MODE_ALLOWED);
		} catch (PackageManager.NameNotFoundException e) {
			return true;
		}
	}

	@TargetApi(21)
	private static class RecentUseComparator implements Comparator<UsageStats> {

		@Override
		public int compare(UsageStats lhs, UsageStats rhs) {
			return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed())?-1:(lhs.getLastTimeUsed() == rhs.getLastTimeUsed())?0:1;
		}
	}

	@TargetApi(21)
	private static String getTopPackage(){

		long ts = System.currentTimeMillis();

		UsageStatsManager mUsageStatsManager = (UsageStatsManager)FS.getInstance().getSystemService("usagestats");
		List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-10000, ts);

//		if(usageStats == null)return FS.getInstance().getPackageName();;
//		if(usageStats.size() == 0)return FS.getInstance().getPackageName();;
		
		// 添加跟AppDetialManager#getTopPackage方法同样的逻辑（将最后一次得到的数据存到本地） #ADRIAN.2015.7.24.14.20
		if(usageStats == null)
			return SPUtils.getLastPackageName();
		if(usageStats.size() == 0)
			return SPUtils.getLastPackageName();

		Collections.sort(usageStats, new RecentUseComparator());

		return usageStats.get(0).getPackageName();
	}

	private static String getTopPackageUnderL(){

		ActivityManager am = (ActivityManager) FS.getInstance()
				.getSystemService(android.content.Context.ACTIVITY_SERVICE);
		PackageManager pm = FS.getInstance().getPackageManager();

		List<RecentTaskInfo> tasks = am.getRecentTasks(1, 1);
		if ((tasks == null) || (tasks.size() == 0)) {
			return FS.getInstance().getPackageName();
		}        
		//
		RecentTaskInfo info = tasks.get(0);
		Intent it = info.baseIntent;
		ResolveInfo ri = pm.resolveActivity(it, 0);
		if (ri != null) {
			return ri.activityInfo.packageName;            
		}
		//
		return FS.getInstance().getPackageName();
	}

	/**
	 * 情况：
	 * 1. 家长端第一次请求孩子端的数据
	 * 2. 奖章段更换用户又更新回来
	 * 功能：
	 * 1. 得到当前应用程序的包名
	 * @param c
	 * @return
	 * @author ADRIAN.2015.7.24.14.10
	 */
	public static String getTopPackageName(Context c) {
		boolean b = false;
		// TODO
//		String pkgname = FS.getInstance().getPackageName();
		String pkgname = SPUtils.getLastPackageName();
		//
		if (Build.VERSION.SDK_INT >= 21) {
			if (!needPermissionForBlocking(FS.getInstance())) {
				pkgname = getTopPackage();
				b = true;
			}
		}
		//
		if (!b) {
			pkgname = getTopPackageUnderL();
		}
		//
		return pkgname;
	}

	/**
	 * 返回应用名称
	 */
	public static String getAppName(Context c,String packageName) {
		PackageManager pm = c.getPackageManager();
		String strName = packageName;
		try {
			ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
			strName = pm.getApplicationLabel(ai).toString();
		} catch (NameNotFoundException e) {
			L.e("maf", "error--", e);
		}
		return strName;
	}

	public static Drawable getAppIcon(Context c,String packageName) {
		PackageManager pm = c.getPackageManager();
		Drawable icon = null;
		try {
			icon = pm.getApplicationIcon(packageName);
		} catch (NameNotFoundException e) {
			L.e("maf", "error--", e);
		}
		return icon;
	}

	public static void startApp(Context c, NewMessageEntity msg){
		if(msg.getPackageName().equals(FS.getInstance().getPackageName())){
			if(msg.getText().equals("一条新消息")){
				SPUtils.savePageNum(2);
				Intent toMsg = new Intent(c, FrameworkActivity.class);
				toMsg.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				c.startActivity(toMsg);
			}else{
				Intent intent = new Intent(c, FrameworkActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				c.startActivity(intent);
			}
		}else{
			PackageManager pm = c.getPackageManager();
			Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
			resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			resolveIntent.setPackage(msg.getPackageName());
			List<ResolveInfo> resolveInfoList = pm
					.queryIntentActivities(resolveIntent, 0);
			if (resolveInfoList != null && resolveInfoList.size() > 0) {
				ResolveInfo resolveInfo = resolveInfoList.get(0);
				String activityPackageName = resolveInfo.activityInfo.packageName;
				String className = resolveInfo.activityInfo.name;
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				ComponentName componentName = new ComponentName(
						activityPackageName, className);
				intent.setComponent(componentName);
				c.startActivity(intent);
			}
		}
	}
	
	public static boolean isContain(String msgPkg){
		for(String pkg : pkgs){
			if(msgPkg.equalsIgnoreCase(pkg)){
				return true;
			}
		}
		return false;
	}
	
//	public static List<String> getPkgList(){
//		List<String> pkgList = new ArrayList<String>();
//		//获取电话包名
//		Intent infoIntent = new Intent(Intent.ACTION_DIAL);
//		ResolveInfo res = FS.getInstance().getPackageManager().resolveActivity(infoIntent, 0);
//		if (res != null) {
//			pkgList.add(res.activityInfo.packageName);
//		}
//		//获取短信包名
//		Uri uri = Uri.parse("smsto:10086");  
//		infoIntent = new Intent(Intent.ACTION_SENDTO, uri);
//		ResolveInfo res2 = FS.getInstance().getPackageManager().resolveActivity(infoIntent, 0);
//		if (res != null) {
//			pkgList.add(res2.activityInfo.packageName);
//		}
//		for(String pkg : pkgs){
//			pkgList.add(pkg);
//		}
//		return pkgList;
//	}
	
	//获取电话包名
	public static String getPhoneAppPkg(){
		String phoneApp = "";
		Intent infoIntent = new Intent(Intent.ACTION_DIAL);
		ResolveInfo res = FS.getInstance().getPackageManager().resolveActivity(infoIntent, 0);
		if (res != null) {
			phoneApp = res.activityInfo.packageName;
		}
		return phoneApp;
	}
	
	public static String getSMSAppPkg(){
		String SMSApp = "";
		Uri uri = Uri.parse("smsto:10086");  
		Intent infoIntent = new Intent(Intent.ACTION_SENDTO, uri);
		ResolveInfo res = FS.getInstance().getPackageManager().resolveActivity(infoIntent, 0);
		if (res != null) {
			SMSApp = res.activityInfo.packageName;
		}
		return SMSApp;
	}
}
